package com.hc.music.controller;

import com.alibaba.excel.EasyExcel;
import com.hc.music.common.R;
import com.hc.music.entity.ListSong;
import com.hc.music.entity.SongList;
import com.hc.music.service.ListSongService;
import com.hc.music.service.SongListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.util.List;

@RestController
@RequestMapping("listSong")
public class ListSongController {
    @Autowired
    ListSongService listSongService;

    @Autowired
    SongListService songListService;

    @RequestMapping("addListSong")
    public R addListSong(@RequestBody ListSong listSong){
        return listSongService.addListSong(listSong);
    }

    @RequestMapping("allListSong")
    public List<ListSong> allListSong(){
        return listSongService.allListSong();
    }

    @RequestMapping("selectSongListId")
    public R listSongOfSongId(@RequestParam Integer id){
        return listSongService.listSongOfSongId(id);
    }

    @RequestMapping("deleteSongIdInListSong")
    public R deleteSongIdInListSong(@RequestParam Integer songId ,@RequestParam Integer songListId){
        return listSongService.deleteListSong(songId,songListId);
    }

    @RequestMapping("excle")
    public ResponseEntity<Resource> excle() throws Exception {
        String fileName = "SongList" + System.currentTimeMillis() + ".xlsx";
        File file = new File(System.getProperty("user.dir")+System.getProperty("file.separator")+"excel"+System.getProperty("file.separator") + fileName);
        if(!file.exists()){
            file.createNewFile();
        }
        EasyExcel.write(file, SongList.class).sheet("模板").doWrite(getAllSongList());
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file);
        byte[] content = Files.readAllBytes(file.toPath());
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(content.length)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    private List<SongList> getAllSongList(){
        return songListService.findAllSong();
    }
}
